// pages/travel/list/index.ts
import { travelApi } from '../../../utils/api';

Page({
  data: {
    travelRecords: [] as any[],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
  },

  onLoad() {
    this.loadTravelRecords();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
    });
    this.loadTravelRecords(true).then(() => {
      wx.stopPullDownRefresh();
    }).catch(() => {
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreRecords();
    }
  },

  async loadTravelRecords(isRefresh = false) {
    if (this.data.loading) return;

    this.setData({ loading: true });

    try {
      const params = {
        page: isRefresh ? 1 : this.data.page,
        page_size: this.data.pageSize,
      };

      const records: any = await travelApi.getList(params);
      
      if (isRefresh) {
        this.setData({
          travelRecords: records.results || records,
          hasMore: records.next !== null && records.next !== undefined,
        });
      } else {
        this.setData({
          travelRecords: this.data.travelRecords.concat(records.results || records),
          hasMore: records.next !== null && records.next !== undefined,
        });
      }

      if (records.next !== null && records.next !== undefined) {
        this.setData({
          page: this.data.page + 1,
        });
      }

    } catch (error) {
      console.error('加载旅游记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  async loadMoreRecords() {
    if (!this.data.hasMore || this.data.loading) return;
    await this.loadTravelRecords();
  },

  onViewDetail(e: any) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/travel/detail/index?id=${id}`,
    });
  },

  onEditRecord(e: any) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/travel/edit/index?id=${id}`,
    });
  },

  onCreateRecord() {
    wx.navigateTo({
      url: '/pages/travel/create/index',
    });
  },

  formatDate(dateString: string): string {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  formatTime(dateTimeString: string): string {
    try {
      const date = new Date(dateTimeString);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return '';
      }
      
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    } catch (error) {
      return '';
    }
  },

  truncateText(text: string, maxLength: number = 50): string {
    if (!text) return '';
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  },
});
